<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form action="">
        <input type="text" name="username" value="admin">
        <input type="text" name="password" value="123">
        <input type="file" name="img">

        <input type="submit" value="提交">

        <img src="" alt="">
    </form>
    <script src="/upload/ajax.js"></script>

    <script>
        var form = document.querySelector("form");

        // 获取它的自定义属性
        var fileInput = document.querySelector('input[type="file"]')

        var img = document.querySelector("img");

        fileInput.addEventListener("change",function(e){
            console.log(e.target.files);
            var file = e.target.files[0];

            // 这个括号里面如果写form的话就可以把表单里面的username，password和img给到fd
            var fd = new FormData();

            fd.append("file",file);

            ajax({
                url: "/upload",
                method: "post",
                data: fd,
                contentType: false,
                processData: false,
                success: function(data){
                    console.log(data);
                    img.src = data.url;
                }
            })
        })
        
    </script>
</body>

</html>